package com.freesky.provider.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.freesky.common.dao.entity.Item;
import com.freesky.common.dao.entity.ItemCat;
import com.freesky.common.dao.entity.ItemDesc;
import com.freesky.common.enums.RedisKeyEnum;
import com.freesky.common.enums.ResponseEnum;
import com.freesky.common.exception.EMallException;
import com.freesky.common.exception.MyException;
import com.freesky.common.pojo.DataTablesResult;
import com.freesky.common.redis.IRedisTemplate;
import com.freesky.common.redis.RedisExpireTime;
import com.freesky.common.utils.UUIDUtil;
import com.freesky.common.utils.reponse.JSONResponse;
import com.freesky.common.utils.reponse.JSONResponseDiretor;
import com.freesky.common.vo.AllGoodsResult;
import com.freesky.common.vo.VOItem;
import com.freesky.common.vo.VOProductDet;
import com.freesky.provider.order.service.IItemService;
import com.freesky.provider.order.util.VOUtil;
import com.freesky.provider.order.vo.PortalItem;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.jms.Destination;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Freesky on 2017/7/29.
 */
@Service
@Slf4j
@Transactional
public class ItemServiceImpl implements IItemService {
    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private IRedisTemplate redisTemplate;
    @Value("${img-server.no-pic}")
    private String noPicUrl;
    @Value("${spring.activemq.destination}")
    private String destinationName;

    @Override
    public JSONResponse getItemById(String id) {
        Item item = new Item();
        item.setId(id);
        item = item.selectById();
        VOItem voItem = VOUtil.changeItemToVOItem(item);
        ItemCat itemCat = new ItemCat();
        itemCat.setId(voItem.getCid());
        itemCat = itemCat.selectById();
        voItem.setCname(itemCat.getName());
        ItemDesc itemDesc = new ItemDesc();
        itemDesc.setItemId(id);
        itemDesc = itemDesc.selectById();
        if (itemDesc != null) {
            voItem.setDetail(itemDesc.getItemDesc());
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(voItem);
    }


    @Override
    public DataTablesResult getItemList(int draw, int start, int length, int cid, String search, String orderCol, String orderDir) {

        DataTablesResult result = new DataTablesResult();

        //分页执行查询返回结果
        boolean asc = false;
        if (orderDir.equalsIgnoreCase("asc")) {
            asc = true;
        }
        search = search.trim();
        if (search.length() > 0) {
            search = "%" + search + "%";
        }
        Wrapper<Item> wrapper;
        if (cid != -1) {
            if (search.length() > 0) {
                wrapper = new EntityWrapper<Item>().eq("cid", cid).like("title", search).or().like("sell_point", search).or().like("price", search).or().like("id", search).orderBy(orderCol, asc);
            } else {
                wrapper = new EntityWrapper<Item>().eq("cid", cid).orderBy(orderCol, asc);
            }
        } else {
            if (search.length() > 0) {
                wrapper = new EntityWrapper<Item>().like("title", search).or().like("sell_point", search).or().like("price", search).or().like("id", search).orderBy(orderCol, asc);
            } else {
                wrapper = new EntityWrapper<Item>().orderBy(orderCol, asc);
            }
        }
        Page<Item> itemPage = new Item().selectPage(new Page<>(start / length + 1, length), wrapper);
        result.setRecordsFiltered(itemPage.getTotal());
        result.setRecordsTotal(itemPage.getTotal());
        result.setDraw(draw);
        result.setData(itemPage.getRecords());

        return result;
    }

    @Override
    public DataTablesResult getItemSearchList(int draw, int start, int length, int cid, String search,
                                              String minDate, String maxDate, String orderCol, String orderDir) {

        DataTablesResult result = new DataTablesResult();
        //分页执行查询返回结果
        boolean asc = false;
        if (orderDir.equalsIgnoreCase("asc")) {
            asc = true;
        }
        Page<Item> itemPage = new Page<>();
        if (minDate != null && minDate.length() > 0 && maxDate != null && maxDate.length() > 0) {
            if (cid != -1) {
                itemPage = new Item().selectPage(new Page<>(start / length + 1, length), new EntityWrapper<Item>().between("created", minDate, maxDate).eq("cid", cid).like("title", search).or().like("sell_point", search).or().like("price", search).or().orderBy(orderCol, asc));
            } else {
                itemPage = new Item().selectPage(new Page<>(start / length + 1, length), new EntityWrapper<Item>().between("created", minDate, maxDate).like("title", search).or().like("sell_point", search).or().like("price", search).or().orderBy(orderCol, asc));
            }
        } else {
            if (cid != -1) {
                itemPage = new Item().selectPage(new Page<>(start / length + 1, length), new EntityWrapper<Item>().eq("cid", cid).like("title", search).or().like("sell_point", search).or().like("price", search).or().orderBy(orderCol, asc));
            } else {
                itemPage = new Item().selectPage(new Page<>(start / length + 1, length), new EntityWrapper<Item>().like("title", search).or().like("sell_point", search).or().like("price", search).or().orderBy(orderCol, asc));
            }
        }


        result.setRecordsFiltered(itemPage.getTotal());
        result.setRecordsTotal(itemPage.getSize());
        result.setDraw(draw);
        result.setData(itemPage.getRecords());
        return result;
    }

    @Override
    public DataTablesResult getAllItemCount() {
        int count = new Item().selectCount(new EntityWrapper());
        DataTablesResult result = new DataTablesResult();
        result.setRecordsTotal(Math.toIntExact(count));
        return result;
    }


    public Item getVOItemById(String id) {
        Item item = new Item();
        item.setId(id);
        item = item.selectById();
        return item;
    }

    @Override
    public Item alertItemState(String id, Integer state) {

        Item item = getVOItemById(id);
        item.setStatus(state.byteValue());
        item.setUpdated(new Date());
        boolean update = item.updateById();

        if (!update) {
            throw new EMallException("修改商品状态失败");
        }
        return item;
    }

    @Override
    public JSONResponse deleteItem(String[] ids) {
        for (String id : ids) {
            Item item = new Item();
            item.setId(id);
            boolean delete = item.deleteById();
            if (!delete) {
                throw new EMallException("删除商品失败");
            }
            ItemDesc itemDesc = new ItemDesc();
            itemDesc.setItemId(id);
            boolean deleteItemDesc = itemDesc.deleteById();
            if (!deleteItemDesc) {
                throw new EMallException("删除商品详情失败");
            }
            String msg = "delete" + "," + id;
            sendMessage(msg);
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public JSONResponse addItem(VOItem voItem) {
        String id = UUIDUtil.getUUID();
        Item item = VOUtil.changeVOItemToItem(voItem);
        item.setId(id);
        item.setStatus((byte) 1);
        item.setCreated(new Date());
        item.setUpdated(new Date());
        if (item.getImage().isEmpty()) {
            item.setImage(noPicUrl);
        }
        boolean insertItem = item.insert();
        if (!insertItem) {
            throw new MyException(ResponseEnum.ITEM_ADD_ERROR,null,null);
        }

        ItemDesc itemDesc = new ItemDesc();
        itemDesc.setItemId(id);
        itemDesc.setItemDesc(voItem.getDetail());
        itemDesc.setCreated(new Date());
        itemDesc.setUpdated(new Date());
        boolean insertItemDesc = itemDesc.insert();
        if (!insertItemDesc) {
            throw new MyException(ResponseEnum.ITEM_DESC_ADD_ERROR,null,null);
        }
        String msg = "add" + "," + id;
        sendMessage(msg);
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public JSONResponse updateItem(String id, VOItem voItem) {

        Item oldItem = getVOItemById(id);

        Item item = VOUtil.changeVOItemToItem(voItem);

        if (item.getImage().isEmpty()) {
            item.setImage(oldItem.getImage());
        }
        item.setId(id);
        item.setStatus(oldItem.getStatus());
        item.setCreated(oldItem.getCreated());
        item.setUpdated(new Date());
        boolean updateItem = item.updateById();
        if (!updateItem) {
            throw new MyException(ResponseEnum.ITEM_UPDATE_ERROR,null,null);
        }

        ItemDesc itemDesc = new ItemDesc();

        itemDesc.setItemId(id);
        itemDesc.setItemDesc(voItem.getDetail());
        itemDesc.setUpdated(new Date());
        itemDesc.setCreated(oldItem.getCreated());
        boolean updateItemDesc = itemDesc.updateById();
        if (!updateItemDesc) {
            throw new MyException(ResponseEnum.ITEM_DESC_UPDATE_ERROR,null,null);
        }
        //同步缓存
        deleteProductDetRedis(id);
        String msg = "add" + "," + id;
        sendMessage(msg);
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public JSONResponse getItemDetail(String id) {
        //查询缓存
        VOProductDet detail = redisTemplate.getCacheObject(RedisKeyEnum.ITEM_PREFIX.getKey() + ":" + id, VOProductDet.class);
        if (detail != null) {
            log.info("读取了商品" + id + "详情缓存");
            //重置商品缓存时间
            redisTemplate.expire(RedisKeyEnum.ITEM_PREFIX.getKey() + ":" + id, RedisExpireTime.ITEM);
            return JSONResponseDiretor.buildSuccessJSONResponse(detail);
        }
        Item item = new Item();
        item.setId(id);
        item = item.selectById();
        detail = new VOProductDet();
        detail.setProductId(id);
        detail.setProductName(item.getTitle());
        detail.setSubTitle(item.getSellPoint());
        if (item.getLimitNum() != null && !item.getLimitNum().toString().isEmpty()) {
            detail.setLimitNum(Long.valueOf(item.getLimitNum()));
        } else {
            detail.setLimitNum(Long.valueOf(item.getNum()));
        }
        detail.setSalePrice(item.getPrice());
        ItemDesc itemDesc = new ItemDesc();
        itemDesc.setItemId(id);
        itemDesc = itemDesc.selectById();
        detail.setDetail(itemDesc.getItemDesc());

        if (item.getImage() != null && !item.getImage().isEmpty()) {
            String images[] = item.getImage().split(",");
            detail.setProductImageBig(images[0]);
            List list = new ArrayList();
            for (int i = 0; i < images.length; i++) {
                list.add(images[i]);
            }
            detail.setProductImageSmall(list);
        }
        //无缓存 把结果添加至缓存
        if (detail != null) {
            redisTemplate.putCache(RedisKeyEnum.ITEM_PREFIX.getKey() + ":" + id, JSON.toJSON(detail));
            //设置过期时间
            redisTemplate.expire(RedisKeyEnum.ITEM_PREFIX.getKey() + ":" + id, RedisExpireTime.ITEM);
            log.info("添加了商品" + id + "详情缓存");
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(detail);
    }

    /**
     * 同步商品详情缓存
     *
     * @param id
     */
    public void deleteProductDetRedis(String id) {
        try {
            redisTemplate.delete(RedisKeyEnum.ITEM_PREFIX.getKey() + ":" + id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 发送消息，destination是发送到的队列，message是待发送的消息
     * @param message
     */
    public void sendMessage( final String message){
        log.info("发送消息内容：{}",message);
        Destination destination = new ActiveMQQueue(destinationName);
        jmsTemplate.convertAndSend(destination, message);
    }



    @Override
    public JSONResponse getAll(int page, int size, String sort, Long cid, int priceGt, int priceLte) {

        AllGoodsResult goodsResult = new AllGoodsResult();
        List<PortalItem> list = new ArrayList<>();
        //分页执行查询返回结果
        if (page <= 0) {
            page = 1;
        }
        Page<Item> selectPage;
        //判断条件
        Wrapper<Item> wrapper = new EntityWrapper<Item>()
                .eq(cid !=  null,"cid", cid)
                .eq("status", 1)
                .between(priceGt >0 &&priceLte>0, "price", priceGt, priceLte)
                .orderBy(sort.equals("1"),"price", true);
        selectPage = new Item().selectPage(new Page<>(page, size), wrapper);
        for (Item item : selectPage.getRecords()) {
            PortalItem portalItem= VOUtil.changeItemToPortalItem(item);
            list.add(portalItem);
        }

        goodsResult.setData(list);
        goodsResult.setTotal(selectPage.getTotal());
        return JSONResponseDiretor.buildSuccessJSONResponse(goodsResult);
    }
}

